var express = require("express");
var router = express.Router();
const {
  masterworkerModel,
  relationModel,
  realnameModel,
  userModel,
  releasemodel,
  addressModel,
  payListModel,
  haosaiModel,
  feedbackMessageModel,
} = require("../model/db");
const { alipayModel } = require("../model/db");
const path = require("path");
const multer = require("multer");
const alipaySdk = require("../alipay");
const jwt = require("jsonwebtoken");
const secretKey = "k";
const crypto = require("crypto");
const { log } = require("console");

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/"); // 保存路径
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = `${Date.now()}-${crypto
      .randomBytes(8)
      .toString("hex")}`;
    cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`); // 文件名
  },
});
const upload = multer({ storage: storage });

router.post("/api/upload", upload.array("files[]"), (req, res) => {
  let imglist = [];
  console.log(req.files);
  for (let i of req.files) {
    imglist.push(`http://127.0.0.1:3000/${i.path}`);
  }
  res.send({
    code: 200,
    msg: "上传成功",
    imglist,
  });
});

router.post("/feedbackMessage", async (req, res) => {
  await feedbackMessageModel.create(req.body);
  res.send({
    code: 200,
    msg: "发布成功",
  });
});

/* GET home page. */
router.get("/getWorkerAll", async (req, res) => {
  const woekerDate = await masterworkerModel.find({ status: "1" });
  res.send({
    code: 200,
    data: woekerDate,
  });
});

router.post("/getWorker", async (req, res) => {
  const { currentPage, pageSize, selAddress, worker, distance, search } =
    req.body;
  let workerData = await masterworkerModel.find();
  if (selAddress) {
    workerData = workerData.filter((item) => {
      return item.expectationaddress[0] == selAddress;
    });
  }
  if (worker != "全部" && worker) {
    workerData = workerData.filter((item) => {
      return item.worklist.includes(worker);
    });
  }
  if (search) {
    workerData = workerData.filter((item) => {
      return item.personalsituation.includes(search);
    });
  }
  const total = workerData.length;
  workerData = workerData.slice(0, currentPage * pageSize);
  if (distance == "1") {
    workerData = workerData.sort((a, b) => {
      return a.distance - b.distance;
    });
  }
  if (distance == "2") {
    workerData = workerData.sort((a, b) => {
      return b.distance - a.distance;
    });
  }
  res.send({
    code: 200,
    data: workerData,
    total,
  });
});

router.get("/getWorkerObj", async (req, res) => {
  const obj = await masterworkerModel.findOne({ _id: req.query.id });
  res.send({
    code: 200,
    obj,
  });
});

//用户头像上传
// 配置Multer存储引擎
const fs = require("fs");
// const storage = multer.diskStorage({
//   destination: function (req, file, cb) {
//     const uploadDir = "./uploads";
//     if (!fs.existsSync(uploadDir)) {
//       fs.mkdirSync(uploadDir);
//     }
//     cb(null, uploadDir);
//   },
//   filename: function (req, file, cb) {
//     cb(null, Date.now() + path.extname(file.originalname)); // 重命名文件为时间戳加扩展名
//   },
// });
// const upload = multer({ storage: storage });
// 头像上传路由
router.post("/upload", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.status(400).json({ success: false, message: "未收到文件" });
  }

  // 返回上传成功的响应，包含文件访问路径
  const filePath = `http://${req.headers.host}/uploads/${req.file.filename}`;
  res.json({ success: true, url: filePath });
});

// 支付接口

//发起支付
router.post("/payment", async (req, res) => {
  let orderId = Date.now();
  let name = req.body.name;
  let price = req.body.price;

  let bizContent = {
    out_trade_no: orderId,
    product_code: "FAST_INSTANT_TRADE_PAY",
    total_amount: price,
    subject: name,
  };

  const url = alipaySdk.pageExec("alipay.trade.wap.pay", "GET", {
    bizContent: JSON.stringify(bizContent),
    return_url: "http://localhost:5173/success",
  });

  res.send({
    code: 200,
    url: url,
    success: true,
  });
});

// 定义查询订单的接口路由
router.get("/queryOrder", async (req, res) => {
  const { out_trade_no, trade_no } = req.query;
  try {
    const request = {
      biz_content: {
        out_trade_no,
        trade_no,
      },
    };
    const response = await alipaySdk.exec("alipay.trade.query", request);
    if (response.code === "10000") {
      console.log(response);

      let alipaylist = await alipayModel.create({
        outTradeNo: response.outTradeNo, //商户订单号
        tradeNo: response.tradeNo, //支付宝交易号
        amount: response.totalAmount,
      });
      console.log(alipaylist);

      res.send({
        code: 200,
        msg: "支付成功",
        alipaylist,
        success: true,
      });
    } else if (response.code === "40004") {
      res.status(404).json({
        error: "订单不存在",
        message: "订单查询失败",
      });
    }
  } catch (error) {
    console.error("查询订单时与支付宝交互出错：", error);
    res.status(500).json({
      error: "与支付宝接口交互出现问题",
      message: "订单查询失败",
    });
  }
});

//联系记录
router.get("/relation", async (req, res) => {
  let relation = await relationModel.find();
  res.send({
    code: 200,
    relation,
  });
});

//获取支付宝订单
router.get("/alipay", async (req, res) => {
  try {
    const alipaylist = await alipayModel.find().sort({ createdAt: -1 });
    //计算总金额
    const totalAmount = alipaylist.reduce((sum, item) => sum + item.amount, 0);
    res.send({
      code: 200,
      alipaylist,
      totalAmount,
    });
  } catch (error) {
    console.error("查询支付宝订单时出错：", error);
    res.status(500).json({
      error: "查询支付宝订单时出错",
      message: "查询支付宝订单失败",
    });
  }
});

const request = require("request");
const AK = "kKjQYLPw0iyy7A9PkHxlbjOC";
const SK = "dZ2KnrkYiXWtiYm6xFRVezZYOfVR5OO8";

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken() {
  let options = {
    method: "POST",
    url:
      "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" +
      AK +
      "&client_secret=" +
      SK,
  };
  return new Promise((resolve, reject) => {
    request(options, (error, response) => {
      if (error) {
        reject(error);
      } else {
        resolve(JSON.parse(response.body).access_token);
      }
    });
  });
}

//实名认证
router.post("/wzsb", async (req, res) => {
  let { b64, userid } = req.body;
  console.log(b64);

  var options = {
    method: "POST",
    url:
      "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" +
      (await getAccessToken()),
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      Accept: "application/json",
    },
    // image 可以通过 getFileContentAsBase64("C:\fakepath\0000000.jpg") 方法获取,
    form: {
      id_card_side: "front",
      image: b64,
      detect_ps: "false",
      detect_risk: "false",
      detect_quality: "false",
      detect_photo: "false",
      detect_card: "false",
      detect_direction: "false",
    },
  };

  request(options, async function (error, response) {
    if (error) {
      res.send({
        code: 500,
        msg: "识别失败",
      });

      throw new Error(error);
    }

    let { words_result } = JSON.parse(response.body);
    console.log(response.body);

    // let index=await realnameModel.findOne({idcard:words_result.公民身份号码.words})

    // if(index){
    //   res.send({
    //     code:200,
    //     msg:'已实名'
    //   })
    //   return
    // }
    // await realnameModel.create({
    //   idcard: words_result.公民身份号码.words,
    //   name: words_result.姓名.words,
    //   uid:userid
    // })

    res.send({
      code: 200,
      msg: "认证成功",
      data: words_result,
    });
  });
});
//登录
// 刷新token
router.post("/refresh", (req, res) => {
  const { refreshToken } = req.body;
  if (refreshToken == null) return res.sendStatus(401);
  jwt.verify(refreshToken, secretKey, (err, user) => {
    if (err) return res.sendStatus(403);
    const accessToken = jwt.sign(
      { username: user.username, password: user.password },
      secretKey,
      { expiresIn: 60 * 15 }
    );
    res.send({ accessToken });
  });
});

router.post("/adduser", async (req, res) => {
  let { username, password } = req.body;
  let list = await userModel.find({ username, password });
  console.log(list);
  if (list.length > 0) {
    res.send({
      code: 400,
    });
  } else {
    userModel.create(req.body);
    res.send({
      code: 200,
    });
  }
});

router.get("/login", async (req, res) => {
  let { username, password } = req.query;
  let list = await userModel.find({ username, password });
  console.log(list, "11111111111");
  if (list.length <= 0) {
    res.send({
      code: 400,
    });
  } else {
    const accessToken = jwt.sign({ username, password }, secretKey, {
      expiresIn: 60 * 15,
    });
    const refreshToken = jwt.sign({ username, password }, secretKey, {
      expiresIn: "7d",
    });
    res.send({
      code: 200,
      token: { accessToken, refreshToken },
    });
  }
});

//添加
// const storage = multer.diskStorage({
//   destination: function (req, file, cb) {
//     cb(null, 'uploads/'); // 保存路径
//   },
//   filename: function (req, file, cb) {
//     const uniqueSuffix = `${Date.now()}-${crypto.randomBytes(8).toString('hex')}`;
//     cb(null, `${uniqueSuffix}${path.extname(file.originalname)}`); // 文件名
//   }
// });

// const upload = multer({ storage: storage });

router.post("/api/upload", upload.array("files[]"), (req, res) => {
  let imglist = [];
  for (let i of req.files) {
    imglist.push(`http://127.0.0.1:3000/${i.path}`);
  }
  res.send({
    code: 200,
    msg: "上传成功",
    imglist,
  });
});

router.post("/addrelease", async (req, res) => {
  await releasemodel.create(req.body);
  res.send({
    code: 200,
    msg: "发布成功",
  });
});

router.get("/getrelease", async (req, res) => {
  let data = await releasemodel.find();
  res.send({
    code: 200,
    msg: "获取成功",
    data,
  });
});

router.post("/getreleaseone", async (req, res) => {
  let { id } = req.body;
  let data = await releasemodel.findOne({ _id: id });
  res.send({
    code: 200,
    msg: "获取成功",
    data,
  });
});

function authenticate(req, res, next) {
  // 这里应该包含你的认证逻辑，例如检查 JWT 或会话
  next(); // 如果认证成功，则调用 next()
}

router.post("/api/delete-images", authenticate, async (req, res) => {
  try {
    const { filenames } = req.body; // 假设前端发送的是一个文件名数组

    if (!Array.isArray(filenames) || filenames.length === 0) {
      return res
        .status(400)
        .json({ error: "Invalid or empty filenames array." });
    }

    // 删除每个文件并收集结果
    const results = await Promise.all(
      filenames.map(async (filename) => {
        const filePath = path.join(__dirname, "uploads", filename);

        try {
          // 检查文件是否存在
          await fs.access(filePath);
          // 删除文件
          await fs.unlink(filePath);
          return { filename, status: "deleted" };
        } catch (error) {
          if (error.code === "ENOENT") {
            return { filename, status: "not found" };
          }
          throw error;
        }
      })
    );

    // 检查是否有任何错误
    const errors = results.filter((result) => result.status !== "deleted");
    if (errors.length > 0) {
      return res
        .status(207)
        .json({ message: "Some files were not deleted.", details: errors });
    }

    res
      .status(200)
      .json({ message: "All images deleted successfully.", details: results });
  } catch (error) {
    res
      .status(500)
      .json({ error: "An error occurred while deleting the files." });
  }
});

router.post("/editrelease", async (req, res) => {
  let { id, ...a } = req.body;
  console.log({ ...a });
  await releasemodel.updateOne({ _id: id }, { ...a });
  res.send({
    code: 200,
    msg: "修改成功",
  });
});

router.post("/editflag", async (req, res) => {
  let { id } = req.body;
  let a = await releasemodel.findOne({ _id: id });
  let data = { ...a._doc };
  if (data.isFlag === "1") {
    data.isFlag = "0";
  } else {
    data.isFlag = "1";
  }
  await releasemodel.updateOne({ _id: id }, { ...data });
  res.send({
    code: 200,
  });
});
//师傅API
router.get("/address", async (req, res) => {
  let address = await addressModel.find();
  res.send({
    code: 200,
    address,
  });
});
router.get("/shifuFitment", async (req, res) => {
  let shifuFitment = await releasemodel.find();
  res.send({
    code: 200,
    shifuFitment,
  });
});
router.get("/shifuFitmentDetail", async (req, res) => {
  let { id } = req.query;
  let shifuFitment = await releasemodel.find({ _id: id });
  res.send({
    code: 200,
    shifuFitment: shifuFitment[0],
  });
});
router.post("/addMasterWorker", (req, res) => {
  let expectationaddress = [];
  let worklist = [];
  req.body.expectationaddress.forEach((element) => {
    expectationaddress.push(element.name);
  });
  req.body.worklist.forEach((element) => {
    worklist.push(element.name);
  });
  req.body.expectationaddress = expectationaddress;
  req.body.worklist = worklist;
  req.body.expectedsalary = Number(req.body.expectedsalary);
  console.log(req.body);
  masterworkerModel.create(req.body);
  res.send({
    code: 200,
    msg: "添加成功",
  });
});
router.post("/pay", (req, res) => {
  payListModel.create(req.body);
  console.log(req.body);

  // 前端给后端的数据（订单号，金额，商品描述等信息）
  let orderId = req.body.time;
  let orderMoney = req.body.price;
  let orderTitle = req.body.name;
  //   let orderInfo = req.body.orderInfo;
  // 对接支付宝
  const formData = new AlipayFromData();
  formData.setMethod("get");

  formData.addField("returnUrl", "http://localhost:5173/payy"); // 付款成功打开的链接
  formData.addField("bizContent", {
    // 传递的订单号
    outTradeNo: orderId,
    productCode: "FAST_INSTANT_TRADE_PAY",
    // 金额
    total_amount: orderMoney,
    // 商品标题
    subject: orderTitle,
    // 商品描述
    body: "666",
  });

  const result = alipaySdk.exec(
    "alipay.trade.wap.pay",
    {},
    { formData: formData }
  );

  result.then((resp) => {
    res.send({
      success: "支付成功",
      code: 200,
      result: resp,
    });
  });
});

router.get("/payy", async function (req, res, next) {
  let data = await payListModel.find();

  res.send({
    code: 200,
    msg: "支付成功",
    data,
    dataLength: data.length,
  });
});
router.post("/authenticate-id-card", async (req, res) => {
  // const idCardInfo = req.body;
  const appCode = "294044b2d8034f26b7874e162d736cb3"; // 替换为你的阿里云AppCode
  const alibabaApiUrl =
    "https://idenauthen.market.alicloudapi.com/idenAuthentication"; // 替换为实际的API URL

  try {
    const aliyunResponse = await axios.post(
      alibabaApiUrl,
      {
        idCard: "13062220050213361X",
        name: "郝赛",
        // 其他需要传递的参数
      },
      {
        headers: {
          Authorization: `AppCode ${appCode}`,
        },
      }
    );
    res.json(aliyunResponse.data);
    console.log(111);
  } catch (error) {
    console.log(222);
    res.status(500).send("Error authenticating ID card");
  }
});
//----------------------------------------------------------------
// const upload = multer({ dest: "uploads/" });
//----------------------------------------------------------------
// 假设悦眼AI引擎的API端点和密钥
const aiEngineUrl = "http://www.ybinsure.com/s/api/ocr/identityCard";
const apiKey = "APPID_P4mb7D7yJHfh44ry";

router.post("/identify", upload.single("idcardImage"), async (req, res) => {
  const file = req.body.c;

  if (!file) {
    return res.status(400).send("No file uploaded.");
  }
  const fileContent = fs.readFileSync(file);
  console.log(fileContent);
  const base64Image = fileContent.toString("base64");
});

router.get("/phonjl", async (req, res) => {
  let data = await releasemodel.find();

  res.send({
    msg: "cg",

    code: 200,
    data: data,
  });
});
router.get("/mas", async (req, res) => {
  let data = await masterworkerModel.find();

  res.send({
    msg: "cg",
    code: 200,
    data: data,
  });
});

router.post("/haosaiadd", async (req, res) => {
  await haosaiModel.create(req.body);

  res.send({
    msg: "cg",
    code: 200,
  });
});
router.post("/haosaiup", async (req, res) => {
  let _id = req.body._id;

  console.log(11111, req.body, _id);

  await haosaiModel.updateOne({ _id: _id }, req.body);

  res.send({
    msg: "cg",
    code: 200,
  });
});
router.get("/haosai", async (req, res) => {
  let data = await haosaiModel.find();

  res.send({
    msg: "cg",
    code: 200,
    data,
  });
});
module.exports = router;
